<?php
/**
 * Created by : PhpStorm
 * Message: 后台首页控制器
 * User: bingdi
 * Time: 2020/2/1814:42
 * motto: 现在的努力是为了小时候吹过的牛逼!
 */

namespace app\admin\controller;


use app\BaseController;
use app\common\model\UserBookError;
use think\facade\Db;
use think\facade\View;
use think\route\dispatch\Controller;

class Book extends AdminBase
{
    /**\
     * 书籍库
     */
    public function index()
    {
        $name = input('param.name', '', 'trim');
        $where = [];
        if (!empty($name)) {
            $where[] = [
                'name', 'like', '%' . $name . '%'
            ];
        }
        $model = Db::name('book')
            ->where($where)
            ->order(['id' => 'desc'])
            ->limit(1500)
            ->column('id,name,img,price,good_book_id,isbn,author,num');
        foreach ($model as $k => $v) {
            if (!$v['author'] || $v['price'] == "0.00") {
                $model[$k]['is_hegui'] = 2;
            } else {
                $model[$k]['is_hegui'] = 1;
            }
        }
        return View::fetch("index", ['model' => $model, 'name' => $name]);
    }

    /**\
     * 书籍库修改
     */
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            //判断是否为修改
            //修改就一步
            $data['update_time'] = time();
            unset($data['editorValue']);
            Db::startTrans();
            try {
                //找到修改之后的名字好书库是否存在同名,存在则绑定上好书id
//                $res = Db::name('good_book')
//                    ->where(['name' => $data['name']])
//                    ->value('id');
//                if ($res) {
//                    $data['good_book_id'] = $res;
//                }
                //找到作者的id
//                $data['author'] = trim($data['author']);
                //先去查找作者
//                $author = Db::name('author')
//                    ->where(['name' => $data['author']])
//                    ->find();
//                if (!$author) {
//                    //不存在则写入
//                    $author_id = Db::name('author')
//                        ->insertGetId(['name' => $data['author'], 'create_time' => time(), 'update_time' => time()]);
//                } else {
//                    $author_id = $author['id'];
//                }
//                $data['author_id'] = $author_id;
                Db::name('book')
                    ->where('id', $data['id'])
                    ->update($data);
                Db::name('user_book')
                    ->where(['book_id' => $data['id']])
                    ->update(['img' => $data['img'],
                        'name' => $data['name'],
                        'author' => $data['author'],
                        'publisher' => $data['publisher'],
                        'pub_date' => $data['pub_date'],
                        'price' => $data['price'],
                        'page' => $data['page'],
                        'gist' => $data['gist'],
                    ]);
                Db::commit();
                return show(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                return show(0, $e->getMessage());
            }

        } else {
            $id = input('id');
            $model = Db::name('book')
                ->where('id', $id)
                ->find();
            return View::fetch('edit', ['model' => $model]);
        }
    }

    /**\
     * @return string
     * 好书库
     */
    public function good_book_index()
    {
        $model = Db::name('good_book')
            ->order(['status' => 'asc', 'id' => 'desc'])
//            ->order(['id'=>'desc'])
            ->column('id,name,img,status,price,jd_price,dd_price,create_time,publisher');
        return View::fetch("good_book_index", ['model' => $model]);
    }

    /**\
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 查询书籍
     */
    public function query()
    {
        $isbn = input('get.isbn');
        //先查询本地书籍库是否有
        $isbn_num = strlen($isbn);
        if ($isbn_num == 13) {
            $isbn_num = "isbn";
        } else {
            $isbn_num = "isbn10";
        }
        $book = Db::name('book')
            ->where([$isbn_num => $isbn])
            ->find();
        if ($book) {
            return show(1, '', $book);
        } else {
            $book = isbn_query($isbn);
            $book = $book['details'][0];
            if ($book) {
                //第一步写入到书籍库
                Db::startTrans();
                try {
                    //先去查找作者
                    $author = Db::name('author')
                        ->where(['name' => $book['author']])
                        ->lock(true)
                        ->find();
                    if (!$author) {
                        //不存在则写入
                        $author_id = Db::name('author')
                            ->insertGetId(['name' => $book['author'], 'create_time' => time(), 'update_time' => time()]);
                    } else {
                        $author_id = $author['id'];
                    }
                    $book_result['name'] = $book['title'];
                    $book_result['author'] = $book['author'];
                    $book_result['publisher'] = $book['publisher'];
                    $book_result['pub_date'] = $book['pubDate'];
                    $book_result['isbn'] = $book['isbn'];
                    $book_result['isbn10'] = !empty($book['isbn10']) ? $book['isbn10'] : "";
                    $book_result['price'] = $book['price'];
                    $book_result['word_num'] = !empty($book['wordNum']) ? $book['wordNum'] : "";
                    $book_result['page'] = $book['page'];
                    $book_result['img'] = $book['img'];
                    $book_result['small_img'] = !empty($book['smallImg']) ? $book['smallImg'] : "";
                    $book_result['book_catalog'] = !empty($book['bookCatalog']) ? $book['bookCatalog'] : "";
                    $book_result['gist'] = $book['gist'];
                    $book_result['author_id'] = $author_id;
                    $book_result['create_time'] = time();
                    $book_result['update_time'] = time();
                    $book_id = Db::name('book')
                        ->insertGetId($book_result);
                    $book_result['id'] = $book_id;
                    Db::commit();
                    return show(1, '查询成功', $book_result);
                } catch (\Exception $e) {
                    Db::rollback();
                    return show(0, $e->getMessage());
                }

            } else {
                return show(0, '查询失败');
            }
        }

    }

    public function status()
    {
        $data = input('post.');
        $model = Db::name('goods')
            ->where('id', $data['id'])
            ->update(['status' => $data['status']]);
        if (!$model) {
            return show(0);
        }
        return show(1);
    }

    /**\
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 好书修改
     */
    public function good_add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            //判断是否为修改
            if ($data['id']) {
                //修改就一步
                $data['update_time'] = time();
                $res = Db::name('good_book')
                    ->where('id', $data['id'])
                    ->update($data);
            } else {
                Db::startTrans();
                try {
                    //新增到好书库
                    $data['create_time'] = time();
                    $id = Db::name('good_book')
                        ->insertGetId($data);
                    //第三步找到所有书籍库里相同名字的书进行id绑定
                    $book_id_arr = Db::name('book')
                        ->where(['name' => $data['name']])
                        ->column('id');
                    if ($book_id_arr) {
                        Db::name('book')
                            ->where(['id' => $book_id_arr])
                            ->update(['good_book_id' => $id]);
                    }
                    Db::commit();
                    return show(1, '保存成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    return show(0, $e->getMessage());
                }
            }
            if (!$res) {
                return show(0, '数据保存失败');
            }
            //添加到好书库


            return show(1, '数据保存成功');
        } else {
            $id = input('id');
            $model = Db::name('good_book')
                ->where('id', $id)
                ->find();
            return View::fetch('good_add', ['model' => $model]);
        }
    }

    /**\
     * 作者列表
     */
    public function author_index()
    {
        $model = Db::name('author')
            ->order(['id' => 'desc'])
            ->column('id,name,brief,create_time');
        return View::fetch("author_index", ['model' => $model]);
    }

    /**\
     * 作者删除
     */
    public function author_delete()
    {
        $id = input('get.id');
        $author_id = input('get.author_id');
        if (!$author_id) {
            return show(0, '请填写要修改的id');
        }
        Db::startTrans();
        try {
            Db::name('author')->where('id', $id)->delete();
//            $id=Db::name('book')->where('author_id',$id)->column('id');
            Db::name('book')->where(['author_id' => $id])->update(['author_id' => $author_id, 'update_time' => time()]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }

    /**\
     * 作者修改
     */
    public function author_add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            //判断是否为修改
            //修改就一步
            $data['update_time'] = time();
            $res = Db::name('author')
                ->where('id', $data['id'])
                ->update($data);
            if (!$res) {
                return show(0, '数据保存失败');
            }
            return show(1, '数据保存成功');
        } else {
            $id = input('id');
            $model = Db::name('author')
                ->where('id', $id)
                ->find();
            return View::fetch('author_add', ['model' => $model]);
        }
    }

    /**\
     * @return string
     * @throws \think\db\exception\DbException
     * 首页书推投稿待审核
     */
    public function audit_index()
    {
        $nickname = input('param.nickname', '', 'trim');
        $where = [];
        if (!empty($nickname)) {
            $where[] = [
                'b.title|u.nickname', 'like', '%' . $nickname . '%'
            ];
        }
        $model = Db::name('home_audit_book')
            ->alias('b')
            ->leftJoin('user u', 'b.user_id=u.id')
            ->where($where)
            ->order(['b.status' => 'asc'])
            ->field('b.id,u.id as user_id,u.nickname,b.title,b.status,b.book_name,b.create_time,b.audit_time')
            ->paginate([
                'list_rows' => 20,
                'var_page' => 'page',
                'query' => ["nickname" => $nickname,
                ]
            ])
            ->each(function ($item, $key) {
                $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
                $item['audit_time'] = date("Y-m-d H:i:s", $item['audit_time']);
                $item['status_name'] = \app\common\model\Book::STATUS[$item['status']];
                return $item;
            });
        $page = $model->render();
        // 获取总记录数
        $count = $model->total();
        return View::fetch('audit_index', [
            'model' => $model,
            'nickname' => $nickname,
            'page' => $page,
            'count' => $count
        ]);
    }

    public function normal_index()
    {
        $nickname = input('param.nickname', '', 'trim');
        $where = [];
        if (!empty($nickname)) {
            $where[] = [
                'b.title|u.nickname', 'like', '%' . $nickname . '%'
            ];
        }
        $model = Db::name('home_book')
            ->alias('b')
            ->leftJoin('user u', 'b.user_id=u.id')
            ->where($where)
            ->order(['b.cast_date' => 'desc',])
            ->field('b.id,u.id as user_id,u.nickname,b.title,b.book_name,b.cast_date')
            ->paginate([
                'list_rows' => 20,
                'var_page' => 'page',
                'query' => ["nickname" => $nickname,
                ]
            ])
            ->each(function ($item, $key) {
                return $item;
            });
        $page = $model->render();
        // 获取总记录数
        $count = $model->total();
        return View::fetch('normal_index', [
            'model' => $model,
            'nickname' => $nickname,
            'page' => $page,
            'count' => $count
        ]);
    }

    /**\
     * 审核首页书推投稿
     */
    public function article_detail()
    {
        if (request()->isPost()) {
            $id = input('post.id');
            $cast_date = input('post.cast_date');
            $refuse = input('post.refuse');
            Db::startTrans();
            try {
                $res = Db::name('home_audit_book')
                    ->where('id', $id)
                    ->lock(true)
                    ->find();
                $weekarray = ["日", "一", "二", "三", "四", "五", "六"];
                $week = $weekarray[date('w', strtotime($cast_date))];
                if (empty($refuse)) {
                    Db::name('home_book')
                        ->insert(['create_time' => time(), 'update_time' => time(), 'content' => $res['content'],
                            'title' => $res['title'], 'user_id' => $res['user_id'], 'book_name' => $res['book_name'], 'cast_date' => $cast_date, 'week_day' => $week,
                            'book_id' => $res['book_id']
                        ]);
                    Db::name('home_audit_book')
                        ->where('id', $id)
                        ->update(['status' => 3, 'cast_date' => $cast_date]);
                } else {
                    Db::name('home_audit_book')
                        ->where('id', $id)
                        ->update(['status' => 2, 'refuse' => $refuse]);
                }
                Db::commit();
                return show(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                return show(0, $e->getMessage());
            }
        } else {
            $id = input('id');
            $model = Db::name('home_audit_book')
                ->where('id', $id)
                ->find();
            return View::fetch('article_detail', ['model' => $model]);
        }
    }

    /**\
     * 后台从书籍库添加好书库
     */
    public function add_good_book()
    {
        $data = input('post.');
        Db::startTrans();
        try {
            //增加到好书库
            //找到书籍信息
            $book = Db::name('book')
                ->where(['id' => $data['id'], 'good_book_id' => 0])
                ->lock(true)
                ->find();
            if (!$book) {
                return show(0, '此书不可设为好书');
            }
            $result['name'] = $book['name'];
            $result['isbn'] = $book['isbn'];
            $result['isbn10'] = $book['isbn10'];
            $result['price'] = $book['price'];
            $result['jd_price'] = $data['price'];
            $result['create_time'] = time();
            $result['update_time'] = time();
            $result['author'] = $book['author'];
            $result['translator'] = $book['translator'];
            $result['publisher'] = $book['publisher'];
            $result['img'] = $book['img'];
            $id = Db::name('good_book')
                ->insertGetId($result);
            //给所有相同名字的好书库绑定上id
            Db::name('book')
                ->where(['name' => $book['name']])
                ->update(['good_book_id' => $id]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }

    /**
     * 批量上传好书
     */
    public function add_good_book_arr()
    {
        if (request()->isPost()) {
            $data = input('post.');
            Db::startTrans();
            try {
                //增加到好书库
                //找到书籍信息
                $book = Db::name('book')
                    ->where(['id' => $data['id'], 'good_book_id' => 0])
                    ->lock(true)
                    ->find();
                if (!$book) {
                    return show(0, '此书不可设为好书');
                }
                $result['name'] = $book['name'];
                $result['isbn'] = $book['isbn'];
                $result['isbn10'] = $book['isbn10'];
                $result['price'] = $book['price'];
                $result['jd_price'] = 0;
                $result['create_time'] = time();
                $result['update_time'] = time();
                $result['author'] = $book['author'];
                $result['translator'] = $book['translator'];
                $result['publisher'] = $book['publisher'];
                $result['img'] = $book['img'];
                $id = Db::name('good_book')
                    ->insertGetId($result);
                //给所有相同名字的好书库绑定上id
                Db::name('book')
                    ->where(['name' => $book['name']])
                    ->update(['good_book_id' => $id]);
                Db::commit();
                return show(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                return show(0, $e->getMessage());
            }
        } else {
            return view('add_book');
        }
    }

    /**\
     * 书籍库top250
     */
    public function top_index()
    {
        $name = input('param.name', '', 'trim');
        $where = [];
        if (!empty($name)) {
            $where[] = [
                'name', 'like', '%' . $name . '%'
            ];
        }
        $model = Db::name('book')
            ->where($where)
            ->where('rank', '>', 0)
            ->order(['rank' => 'asc'])
            ->limit(250)
            ->column('id,name,img,price,good_book_id,isbn,author,num,rank');
        foreach ($model as $k => $v) {
            if (!$v['author'] || $v['price'] == "0.00") {
                $model[$k]['is_hegui'] = 2;
            } else {
                $model[$k]['is_hegui'] = 1;
            }
        }
        return View::fetch("top_index", ['model' => $model, 'name' => $name]);
    }

    /**\
     * 书籍库top250假
     */
    public function top_index_faker()
    {
        $name = input('param.name', '', 'trim');
        $where = [];
        if (!empty($name)) {
            $where[] = [
                'f.name', 'like', '%' . $name . '%'
            ];
        }
        $model = Db::name('book_faker')
            ->alias('f')
            ->leftJoin('book b', 'b.id=f.book_id')
            ->where($where)
            ->where('f.rank', '>', 0)
            ->order(['f.rank' => 'asc'])
            ->limit(250)
            ->column('b.id,b.name,b.img,b.price,b.good_book_id,b.isbn,b.author,f.num,f.rank');
        foreach ($model as $k => $v) {
            if (!$v['author'] || $v['price'] == "0.00") {
                $model[$k]['is_hegui'] = 2;
            } else {
                $model[$k]['is_hegui'] = 1;
            }
        }
        return View::fetch("top_index_faker", ['model' => $model, 'name' => $name]);
    }

    /**\
     * 用户书籍库
     */
    public function user_index()
    {
        $name = input('param.name', '', 'trim');
        $where = [];
        if (!empty($name)) {
            $where[] = [
                'name', 'like', '%' . $name . '%'
            ];
        }
        $model = Db::name('user_book')
            ->where($where)
            ->order(['id' => 'desc'])
            ->limit(1000)
            ->column('id,name,img,price,isbn,author,book_id');
        return View::fetch("user_index", ['model' => $model, 'name' => $name]);
    }

    /**
     * 书籍纠错页面
     */
    public function error_index()
    {
        $name = input('param.name', '', 'trim');
        $where = [];
        if (!empty($name)) {
            $where[] = [
                'e.name', 'like', '%' . $name . '%'
            ];
        }
        $where[] = [
            'e.status', '=',0
        ];
        $model = Db::name('user_book_error')
            ->alias('e')
            ->leftJoin('user u', 'u.id=e.user_id')
            ->where($where)
            ->order(['e.id' => 'desc'])
            ->limit(500)
            ->column('e.id,u.id as user_id,u.nickname,e.isbn,e.type,e.create_time,e.status,e.book_id');
        foreach ($model as $k => $v) {
            $model[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
            $model[$k]['type'] = UserBookError::TYPE[$v['type']];
            $model[$k]['status'] = UserBookError::STATUS[$v['status']];
            if ($v['book_id']){
                $book=Db::name('book')
                    ->where('id',$v['book_id'])
                    ->field('create_time,name')
                    ->find();
                $model[$k]['book_name']=$book['name'];
                $model[$k]['book_create_time']=date("Y-m-d H:i:s",$book['create_time']);
            }else{
                $model[$k]['book_name']='';
                $model[$k]['book_create_time']='';
            }
        }
        return View::fetch("error_index", ['model' => $model, 'name' => $name]);
    }

    /**\
     * 书籍库修改
     */
    public function error_edit()
    {
        if (request()->isPost()) {
            //判断是否还可以审核
            $data = input('post.');
            $res = Db::name('user_book_error')
                ->where(['id' => $data['id'], 'status' => 0])
                ->find();
            if (!$res) {
                return show(0, '此书已审核');
            }
            if ($data['status'] == 2) {
                //如果是拒绝,则判断是否书写原因
                if (!$data['cause']) return show(0, '请填写原因');
                $res = Db::name('user_book_error')
                    ->where('id', $data['id'])
                    ->update(['status' => 2, 'cause' => $data['cause'], 'update_time' => time()]);
                if (!$res) {
                    return show(0, '审核失败');
                }
                return show(1, '审核成功');
            }
            //如果是通过
            Db::startTrans();
            try {
                //找到用户id
                $user = Db::name('user_book_error')
                    ->where('id', $data['id'])
                    ->lock(true)
                    ->find();
                if ($user['type'] == 2) {
                    //先判断是否已经存在
                    $book = Db::name('book')
                        ->where('isbn', $user['isbn'])
                        ->find();
                    if ($book) {
                        //则去走不通过,原因书籍库已存在,如需修改请选择书籍纠错
                        Db::name('user_book_error')
                            ->where('id', $data['id'])
                            ->update(['status' => 2, 'cause' => "书籍库已存在,如需纠错请选择书籍纠错分类", 'update_time' => time()]);
                        Db::commit();
                        return show(1, '保存成功');
                    }
                    //修改审核库
                    Db::name('user_book_error')
                        ->where('id', $data['id'])
                        ->update(['status' => $data['status'], 'update_time' => time()]);
                    //新增书籍信息
                    //寻找作者
//                    $author = Db::name('author')
//                        ->where(['name' => $data['author']])
//                        ->find();
//                    if (!$author) {
//                        //不存在则写入
//                        $author_id = Db::name('author')
//                            ->insertGetId(['name' => $data['author'], 'create_time' => time(), 'update_time' => time()]);
//                    } else {
//                        $author_id = $author['id'];
//                    }
                    $result['name'] = $data['name'];
                    $result['author'] = $data['author'];
                    $result['translator'] = $data['translator'];
                    $result['publisher'] = $data['publisher'];
                    $result['pub_date'] = $data['pub_date'];
                    $result['isbn'] = $user['isbn'];
                    $result['price'] = $data['price'];
                    $result['word_num'] = $data['word_num'];
                    $result['page'] = $data['page'];
                    $result['img'] = $data['img'];
                    $result['gist'] = $data['gist'];
//                    $result['author_id'] = $author_id;
                    $result['create_time'] = time();
                    $result['update_time'] = time();
                    Db::name('book')
                        ->insert($result);
                    //给用户增加经验值
                    //写入经验值表
                    $res = add_empirical($user['user_id'], 6, 10);
                    if (!$res) {
                        Db::rollback();
                        return show(0, '经验值写入失败');
                    }
                    Db::commit();
                    return show(1, '保存成功');
                } else {
                    //先判断是否已经存在
                    $book = Db::name('book')
                        ->where(['isbn' => $user['isbn'], 'id' => $user['book_id']])
                        ->find();
                    if (!$book) {
                        return show(0, '未找到此书籍');
                    }
                    //修改审核库
                    Db::name('user_book_error')
                        ->where('id', $data['id'])
                        ->update(['status' => $data['status'], 'update_time' => time()]);
                    $result = array_filter($data);
//                    if ($data['author']) {
//                        //寻找作者
//                        $author = Db::name('author')
//                            ->where(['name' => $data['author']])
//                            ->find();
//                        if (!$author) {
//                            //不存在则写入
//                            $author_id = Db::name('author')
//                                ->insertGetId(['name' => $data['author'], 'create_time' => time(), 'update_time' => time()]);
//                        } else {
//                            $author_id = $author['id'];
//                        }
//                        $result['author_id'] = $author_id;
//                    }
                    $result['update_time'] = time();
                    unset($result['status']);
                    unset($result['id']);
                    Db::name('book')
                        ->where('id', $book['id'])
                        ->update($result);
                    //修改用户书籍库
                    Db::name('user_book')
                        ->where(['book_id'=>$book['id']])
                        ->update($result);
                    //给用户增加经验值
                    //写入经验值表
                    $res = add_empirical($user['user_id'], 7, 5);
                    if (!$res) {
                        Db::rollback();
                        return show(0, '经验值写入失败');
                    }
                    Db::commit();
                    return show(1, '保存成功');
                }

            } catch (\Exception $e) {
                Db::rollback();
                return show(0, $e->getMessage());
            }
        } else {
            $id = input('id');
            $model = Db::name('user_book_error')
                ->where('id', $id)
                ->find();
            if ($model['type'] == 1) {
                $name = "error_edit_one";
            } else {
                $name = "error_edit_two";
                $model['rest_img'] = \Qiniu\json_decode($model['rest_img']);
            }
            return View::fetch($name, ['model' => $model]);
        }
    }

    /**\
     * 书籍纠错修改
     */
    public function error_edit_one()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if ($data['status'] == 2) {
                //如果是拒绝,则判断是否书写原因
                if (!$data['cause']) return show(0, '请填写原因');
                $res = Db::name('user_book_error')
                    ->where('id', $data['id'])
                    ->update(['status' => 2, 'cause' => $data['cause'], 'update_time' => time()]);
                if (!$res) {
                    return show(0, '审核失败');
                }
                return show(1, '审核成功');
            }
            //如果是通过
            Db::startTrans();
            try {
                //找到用户id
                $user = Db::name('user_book_error')
                    ->where('id', $data['id'])
                    ->lock(true)
                    ->find();

            } catch (\Exception $e) {
                Db::rollback();
                return show(0, $e->getMessage());
            }
        } else {
            $id = input('id');
            $model = Db::name('user_book_error')
                ->where('id', $id)
                ->find();
            if ($model['type'] == 1) {
                $name = "error_edit_one";
            } else {
                $name = "error_edit_two";
                $model['rest_img'] = \Qiniu\json_decode($model['rest_img']);
            }
            return View::fetch($name, ['model' => $model]);
        }
    }
}